<!-- 添加或修改角色配置对话框 -->
<template>
    <div>
        <el-drawer :title="title" v-model="drawerShow" direction="rtl" :before-close="handleClose" size="35%"
            :close-on-click-modal="false">
            <el-form ref="roleRef" :model="form" :rules="formRules" label-width="100px">
                <el-form-item label="所属系统">
                    <el-input v-model="systemData.systemName" disabled controls-position="right" />
                </el-form-item>
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item prop="roleKey">
                    <template #label>
                        <span>
                            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                                <el-icon><question-filled /></el-icon>
                            </el-tooltip>
                            权限字符
                        </span>
                    </template>
                    <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                            dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-checkbox v-model="menuExpand" 
                        @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                    <el-checkbox v-model="menuNodeAll"
                        @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
                    <!-- <el-checkbox v-model="form.menuCheckStrictly"
                        @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
                    <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id"
                        :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候"
                        :props="{ label: 'label', children: 'children' }"></el-tree>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取 消</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>
<script setup>
    import { ref, watch } from "vue"
    import { roleMenuTreeselect, treeselect as menuTreeselect } from "@/api/system/menu";
    const props = defineProps(['show', 'formData', 'title', 'systemInfo']);
    const emit = defineEmits(['update:show', 'submit']);
    const { proxy } = getCurrentInstance();
    const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
    const title = ref(props.title || '角色编辑');
    const drawerShow = ref(false);
    const menuRef = ref(null);
    const form = ref({
        roleName: '',
        roleKey: '',
        roleSort: 10,
        status: "0",
        roleType: '', // 系统关键字
        menuCheckStrictly: true,
        remark: ''
    });
    const formRules = ref({
        roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
        roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
        roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
    });
    const systemData = ref({});
    const menuOptions = ref([]);
    const menuExpand = ref(false);
    const menuNodeAll = ref(false);
    watch(() => props.show, () => {
        drawerShow.value = props.show;
        title.value = props.title;
        if(drawerShow.value){
            getMenuTreeselect();
            systemData.value = props.systemInfo;
            if(props.formData.roleId) {
                setDefaultFormData(props.formData.roleId);
            }
        }
    }, { deep: true });
    /** 查询菜单树结构 */
    const getMenuTreeselect = () => {
        menuTreeselect().then(response => {
            menuOptions.value = response.data;
        });
    }
    /** 树权限（展开/折叠）*/
    const handleCheckedTreeExpand = (value, type) => {
        // if (type == "menu") {
            let treeList = menuOptions.value;
            for (let i = 0; i < treeList.length; i++) {
                menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
            }
        // } else if (type == "dept") {
        //     let treeList = deptOptions.value;
        //     for (let i = 0; i < treeList.length; i++) {
        //         deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
        //     }
        // }
    }
    /** 树权限（全选/全不选） */
    const handleCheckedTreeNodeAll = (value, type) => {
        // if (type == "menu") {
            menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
        // } else if (type == "dept") {
        //     deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
        // }
    }
    /** 树权限（父子联动） */
    const handleCheckedTreeConnect = (value, type) => {
        // if (type == "menu") {
            form.value.menuCheckStrictly = value ? true : false;
        // } else if (type == "dept") {
        //     form.value.deptCheckStrictly = value ? true : false;
        // }
    }
    // 获取当前选择的菜单节点数据
    const getMenuAllCheckedKeys = () => {
        // 目前被选中的菜单节点
        let checkedKeys = menuRef.value.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
    }
    const getRoleMenuTreeselect = (roleId) => {
        return roleMenuTreeselect(roleId).then(response => {
            menuOptions.value = response.menus;
            return response;
        });
    }
    const setDefaultFormData = (roleId) => {
        for(const key in form.value){
            form.value[key] = props.formData[key];
        }
        form.value.roleId = roleId;
        const roleMenu = getRoleMenuTreeselect(roleId);
        nextTick(() => {
            roleMenu.then((res) => {
                let checkedKeys = res.checkedKeys;
                checkedKeys.forEach((v) => {
                    nextTick(() => {
                        menuRef.value.setChecked(v, true, false);
                    });
                });
            });
        });
    };
    const submitForm = () => {
        proxy.$refs["roleRef"].validate(valid => {
            if (valid) {
                if(!form.value.roleType) form.value.roleType = systemData.value.sysTemValue;
                form.value.menuIds = getMenuAllCheckedKeys();
                emit('submit', form);
                handleClose();
            }
        });
    };
    const cancel = () => {
        handleClose();
    };
    const handleClose = () => {
        drawerShow.value = false;
        emit('update:show', false);
        resetForm();
    };
    const resetForm = () => {
        form.value = {
            roleName: '',
            roleKey: '',
            roleSort: 10,
            status: "0",
            roleType: '',
            menuCheckStrictly: true,
            remark: ''
        };
        proxy.resetForm("roleRef");
    }
</script>